import os
import configparser

# 配置文件路径
CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'firealam.conf')

def load_config():
    """加载配置文件"""
    config = configparser.ConfigParser()
    
    # 如果配置文件不存在，创建默认配置
    if not os.path.exists(CONFIG_PATH):
        create_default_config()
    
    config.read(CONFIG_PATH)
    return config

def create_default_config():
    """创建默认配置文件"""
    config = configparser.ConfigParser()
    
    # MQTT配置
    config['MQTT'] = {
        'enabled': 'false',
        'host': 'localhost',
        'port': '1883',
        'username': '',
        'password': '',
        'topic': 'firealarm/status',
        'keepalive': '60'
    }
    
    # 短信配置
    config['SMS'] = {
        'enabled': 'false',
        'service': 'twilio',  # twilio 或 aliyun
        'account_sid': '',
        'auth_token': '',
        'phone_number': '',
        'recipient_number': ''
    }
    
    # 传感器配置
    config['SENSORS'] = {
        'flame_threshold': '1',
        'smoke_threshold': '1',
        'check_interval': '0.5',
        'reset_interval': '7',
        'reset_manual': 'false'
    }
    
    # 保存默认配置
    with open(CONFIG_PATH, 'w') as f:
        config.write(f)
    
    return config

def save_config(config):
    """保存配置到文件"""
    with open(CONFIG_PATH, 'w') as f:
        config.write(f)
    return True